package com.mkj.draw;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @Author Arrebol
 * @Date 2024/8/5 15:47
 * @Project graphical programming
 * @Description：
 * ImageIO演示
 */
public class ReadAndSaveImage {

    private final Frame frame=new Frame("图片查看器");
    private MenuBar menuBar=new MenuBar();
    Menu menu=new Menu("文件");
    MenuItem open = new MenuItem("打开");
    MenuItem save = new MenuItem("另存为");
    //声明BufferedImage对象记录本地存取到内存中的图片
    BufferedImage image;
    private class MyCanvas extends Canvas{
        @Override
        public void paint(Graphics g) {
            g.drawImage(image,0,0,null);
        }
    }
    private MyCanvas drawArea=new MyCanvas();

    public void init(){
        //组装视图
        open.addActionListener(e -> {
            //打开一个文件对话框
            FileDialog dialog=new FileDialog(frame,"打开文件",FileDialog.LOAD);
            dialog.setVisible(true);
            //获取用户选择的图片路径及名称
            String directory = dialog.getDirectory();
            String fileName = dialog.getFile();
            try {
                image = ImageIO.read(new File(directory, fileName));
                drawArea.repaint();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });
        save.addActionListener(e -> {
            //打开一个文件对话框
            FileDialog dialog=new FileDialog(frame,"保存图片",FileDialog.SAVE);
            dialog.setVisible(true);
            //获取用户设置的保存路径以及文件名称
            String directory = dialog.getDirectory();
            String fileName = dialog.getFile();
            try {
                ImageIO.write(image,"JPEG",new File(directory,fileName));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });
        menu.add(open);
        menu.add(save);
        menuBar.add(menu);
        frame.setMenuBar(menuBar);
        frame.add(drawArea);
        frame.setBounds(200,200,740,508);
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public static void main(String[] args) {
        new ReadAndSaveImage().init();
    }
}
